﻿using MediatR;
using RBAC.Domain;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.User;

namespace RBAC.Write.Api.Application.Handler.User
{
    public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly IBaseRepository<UserRoleModel> userroleRepository;
        private readonly ILogger<DeleteUserHandler> logger;

        public DeleteUserHandler(IBaseRepository<UserModel> userRepository, IBaseRepository<UserRoleModel> userroleRepository, ILogger<DeleteUserHandler> logger)
        {
            this.userRepository = userRepository;
            this.userroleRepository = userroleRepository;
            this.logger = logger;
        }
       /// <summary>
       /// 删除用户
       /// </summary>
       /// <param name="request"></param>
       /// <param name="cancellationToken"></param>
       /// <returns></returns>
        public Task<APIResult<int>> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var user = userRepository.GetModel(request.Id);
            user.IsDeleted = true;
            var userrole = userroleRepository.GetALL().Where(x => x.UserId == request.Id).ToList();
            foreach (var item in userrole)
            {
                item.IsDeleted = true;
                userroleRepository.Update(item);
            }
            var r = userRepository.Update(user);
            if (r > 0)
            {
                res.Code = APIEnums.Success;
                res.Msg = "删除成功";
                res.Data = r;
                logger.LogInformation("删除成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Code = APIEnums.Fail;
                res.Msg = "删除失败";
                res.Data = r;
                logger.LogError("删除失败");
                return Task.FromResult(res);
            }
        }
    }
}
